// 简化版存储 hooks
import { ref, watch } from 'vue'

// 简单的存储适配器
export class SimpleStorage {
    static set(key: string, value: any): void {
        try {
            const stringValue = JSON.stringify(value)
            // #ifdef H5
            localStorage.setItem(key, stringValue)
            // #endif
            // #ifdef MP-WEIXIN || APP-PLUS
            uni.setStorageSync(key, stringValue)
            // #endif
        } catch (error) {
            console.error('存储失败:', error)
        }
    }

    static get(key: string): any {
        try {
            let value = null
            // #ifdef H5
            value = localStorage.getItem(key)
            // #endif
            // #ifdef MP-WEIXIN || APP-PLUS
            value = uni.getStorageSync(key)
            // #endif

            return value ? JSON.parse(value) : null
        } catch (error) {
            console.error('读取存储失败:', error)
            return null
        }
    }

    static remove(key: string): void {
        try {
            // #ifdef H5
            localStorage.removeItem(key)
            // #endif
            // #ifdef MP-WEIXIN || APP-PLUS
            uni.removeStorageSync(key)
            // #endif
        } catch (error) {
            console.error('删除存储失败:', error)
        }
    }
}

// 简化的持久化状态
export function useSimpleStorage<T>(key: string, defaultValue: T) {
    // 从存储中读取初始值
    const storedValue = SimpleStorage.get(key)
    const state = ref<T>(storedValue !== null ? storedValue : defaultValue)

    // 监听变化并自动保存
    watch(
        state,
        (newValue) => {
            SimpleStorage.set(key, newValue)
        },
        { deep: true }
    )

    const setValue = (value: T) => {
        state.value = value
    }

    const reset = () => {
        state.value = defaultValue
        SimpleStorage.remove(key)
    }

    return {
        value: state,
        setValue,
        reset
    }
}
